﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ACC.Extensions.PCClient.Helper
{
    public class ListViewFillHelper
    {
            /// <summary>
            /// 为ListView绑定DataTable数据项
            /// </summary>
            /// <param name="dt">DataTable</param>
            /// <param name="lv">ListView控件</param>
            static public void dataTableToListview(DataTable dt, ListView lv)
            {
                if (dt != null)
                {
                    //lv.View = View.Details;
                    lv.GridLines = true;//显示网格线
                    lv.Items.Clear();//所有的项
                    lv.Columns.Clear();//标题
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        lv.Columns.Add(dt.Columns[i].Caption.ToString());//增加标题
                    }
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        ListViewItem lvi = new ListViewItem(dt.Rows[i][0].ToString());
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            // lvi.ImageIndex = 0;
                            lvi.SubItems.Add(dt.Rows[i][j].ToString());
                        }
                        lv.Items.Add(lvi);
                    }
                    lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);//调整列的宽度
                }
            }

            /// <summary>
            /// ListView反向填充DataTable数据项
            /// </summary>
            /// <param name="lv">ListView控件</param>
            /// <param name="dt">DataTable</param>
            static public void listViewToDataTable(ListView lv, DataTable dt)
            {
                DataRow dr;
                dt.Clear();
                dt.Columns.Clear();
                for (int k = 0; k < lv.Columns.Count; k++)
                {
                    dt.Columns.Add(lv.Columns[k].Text.Trim().ToString());//生成DataTable列头
                }
                for (int i = 0; i < lv.Items.Count; i++)
                {
                    dr = dt.NewRow();
                    for (int j = 0; j < lv.Columns.Count; j++)
                    {
                        dr[j] = lv.Items[i].SubItems[j].Text.Trim();
                    }
                    dt.Rows.Add(dr);//每行内容
                }
            }
        }
    
}
